﻿using Aliyun.OpenServices.OpenStorageService;
using PMSWenLvTing.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Utility
{
    public class OSSHelper
    {
        #region 属性区
        static OssClient client = new OssClient(new Uri(PublicStaticObject.endpoint), PublicStaticObject.accessId, PublicStaticObject.accessKey);
        ////所谓的key就是图片的名字
        //const string key = "photoNameXL";
        ////图片的位置，我采用流上传
        //const string fileToUpload = "<path/to/upload>"; 
        #endregion


        /// <summary>
        /// 上传图片到oss
        /// </summary>
        /// <param name="fileName">图片的名字</param>
        /// <param name="img">js获得图片实体对象</param>
        /// <returns>null为上传失败，其他为成功</returns>
        public static string Oss_UploadObject(string fileName, object imageObject)
        {
            if (imageObject == null || string.IsNullOrEmpty(fileName))
            {
                return null;
            }

            //开始将图片上传到oss
            try
            {
                System.Web.HttpPostedFileWrapper img = imageObject as System.Web.HttpPostedFileWrapper;
                var metadata = new ObjectMetadata();
                metadata.CacheControl = "public";
                metadata.ContentType = img.ContentType;
                var res = client.PutObject(PublicStaticObject.bucketName, fileName, img.InputStream, metadata);
                if (res != null && res.ETag != null)
                    return "ok";
                else
                    return null;

            }
            catch (OssException)
            {
                return null;
            }
            catch (Exception)
            {
                return null;
            }

        }

        /// <summary>
        /// 删除一张图片
        /// </summary>
        /// <param name="fileName">图片名称包含后缀</param>
        /// <returns></returns>
        public static void Oss_DeleteObject(string fileName)
        {
            try
            {
                client.DeleteObject(PublicStaticObject.bucketName, fileName);
            }
            catch (Exception)
            {

            }
        }

        /// <summary>
        /// 获取图片在oss的公网地址，全
        /// </summary>
        /// <param name="fileName">本地数据库中存储的图片名称加后缀 例如 a.jpg</param>
        /// <returns></returns>
        public static string Oss_GetImgAddress(string fileName)
        {
            return PublicStaticObject.imgHeader + fileName;
        }

    }
}
